package com.nsgf.library.ui.mine;

import static android.view.View.GONE;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;

import android.app.Dialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.JsonObject;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.binding_recyclerview.adapter.BaseDataBindingAdapter;
import com.kunminx.binding_recyclerview.adapter.SimpleDataBindingAdapter;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.bean.PointListBean;
import com.nsgf.library.data.bean.PointListBean.ListBean;
import com.nsgf.library.data.bean.UserDataBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.StringUtil;
import com.nsgf.library.utils.ToastUtils;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhht.htzx.BR;
import com.zhht.htzx.R;
import com.zhht.htzx.databinding.ActivityMineConsumptionPointsBinding;
import com.zhht.htzx.databinding.ActivityMinePointsBinding;
import com.zhht.htzx.databinding.DialogConsumptionPointExchangeBinding;
import com.zhht.htzx.databinding.DialogPointExchangeBinding;
import com.zhht.htzx.databinding.ItemMineConsumptionPointsDetailsBinding;
import com.zhht.htzx.databinding.ItemMinePointsDetailsBinding;
import com.zhht.htzx.databinding.ItemMinePointsGoodsBinding;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;


/**
 * 消费积分
 */
public class MineConsumptionPointsActivity extends BaseActivity {

    private ConsumptionPointsStates mStates;

    private SimpleDataBindingAdapter<ListBean, ItemMineConsumptionPointsDetailsBinding> mAdapter;

    private AccountRequester mAccountRequester;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(ConsumptionPointsStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new SimpleDataBindingAdapter<ListBean, ItemMineConsumptionPointsDetailsBinding>(this, R.layout.item_mine_consumption_points_details,
                new DiffUtil.ItemCallback<ListBean>() {
                    @Override
                    public boolean areItemsTheSame(@NonNull ListBean oldItem, @NonNull ListBean newItem) {
                        return oldItem.getId() == newItem.getId();
                    }

                    @Override
                    public boolean areContentsTheSame(@NonNull ListBean oldItem, @NonNull ListBean newItem) {

                        if (oldItem.getId() != newItem.getId())
                            return false;
                        if (!oldItem.getCreateTime().equals(newItem.getCreateTime()))
                            return false;
                        if (!oldItem.getTitle().equals(newItem.getTitle()))
                            return false;
                        if (!oldItem.getDescription().equals(newItem.getDescription()))
                            return false;
                        if (oldItem.getPoint() != newItem.getPoint())
                            return false;

                        return true;
                    }
                }) {
            @Override
            protected void onBindItem(ItemMineConsumptionPointsDetailsBinding binding, ListBean item,
                                      RecyclerView.ViewHolder holder) {
                binding.setVm(item);


                if (null != item.getTradeOrderResp()) {
                    SimpleDataBindingAdapter<PointListBean.ListBean.TradeOrderRespBean.ItemsBean
                            , ItemMinePointsGoodsBinding> mAdapterChild =
                            new SimpleDataBindingAdapter<PointListBean.ListBean.TradeOrderRespBean.ItemsBean
                                    , ItemMinePointsGoodsBinding>(MineConsumptionPointsActivity.this,
                                    R.layout.item_mine_points_goods, new DiffUtil.ItemCallback<ListBean.TradeOrderRespBean.ItemsBean>() {
                                @Override
                                public boolean areItemsTheSame(@NonNull ListBean.TradeOrderRespBean.ItemsBean oldItem,
                                                               @NonNull ListBean.TradeOrderRespBean.ItemsBean newItem) {
                                    return false;
                                }

                                @Override
                                public boolean areContentsTheSame(@NonNull ListBean.TradeOrderRespBean.ItemsBean oldItem,
                                                                  @NonNull ListBean.TradeOrderRespBean.ItemsBean newItem) {
                                    return false;
                                }
                            }) {
                                @Override
                                protected void onBindItem(ItemMinePointsGoodsBinding binding,
                                                          PointListBean.ListBean.TradeOrderRespBean.ItemsBean childItem,
                                                          RecyclerView.ViewHolder holder) {
                                    binding.setVm(childItem);
                                    binding.setVmInfo(item.getTradeOrderResp());
                                }
                            };
                    binding.setAdapterChild(mAdapterChild);
                    binding.recyclerView.setVisibility(VISIBLE);
                    mAdapterChild.submitList(item.getTradeOrderResp().getItems());

                } else {
                    binding.recyclerView.setVisibility(GONE);
                }
            }
        };
        return new DataBindingConfig(R.layout.activity_mine_consumption_points, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy())
                .addBindingParam(BR.adapter, mAdapter);
    }

    private ActivityMineConsumptionPointsBinding mBinding;

    private int type = 0;
    private UserDataBean userDataBeanState;

    private int page = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);
        mBinding = (ActivityMineConsumptionPointsBinding) getBinding();
        mStates.titleBar.set(getIntent().getStringExtra("title"));
        type = getIntent().getIntExtra("index", 1);
        userDataBeanState = getIntent().getParcelableExtra("data");
        mAccountRequester.getPointDetail();

        if (type == 1) {

            for (UserDataBean.UserBean.SysConfigListBean sysConfigListBean : userDataBeanState.getSysConfigList()) {

                if (APIs.transfer_of_spending_points_features.equals(sysConfigListBean.getConfigKey())) {
                    if ("1".equals(sysConfigListBean.getConfigValue())) {
                        mBinding.llConsumptionTransfer.setVisibility(VISIBLE);
                    } else {
                        mBinding.llConsumptionTransfer.setVisibility(INVISIBLE);
                    }
                }

                if (APIs.redeem_bonus_points_features.equals(sysConfigListBean.getConfigKey())) {
                    if ("1".equals(sysConfigListBean.getConfigValue())) {
                        mBinding.llConsumptionExchange.setVisibility(VISIBLE);
                    } else {
                        mBinding.llConsumptionExchange.setVisibility(INVISIBLE);
                    }
                }
            }
        } else {
            for (UserDataBean.UserBean.SysConfigListBean sysConfigListBean : userDataBeanState.getSysConfigList()) {

                if (APIs.huitongbao_transfer_features.equals(sysConfigListBean.getConfigKey())) {
                    if ("1".equals(sysConfigListBean.getConfigValue())) {
                        mBinding.llConsumptionTransfer.setVisibility(VISIBLE);
                    } else {
                        mBinding.llConsumptionTransfer.setVisibility(INVISIBLE);
                    }
                }

                if (APIs.huitongbao_for_consumption_points_features.equals(sysConfigListBean.getConfigKey())) {
                    if ("1".equals(sysConfigListBean.getConfigValue())) {
                        mBinding.llConsumptionExchange.setVisibility(VISIBLE);
                    } else {
                        mBinding.llConsumptionExchange.setVisibility(INVISIBLE);
                    }
                }
            }
        }


        mAccountRequester.getSrcSuccess().observe(this, new Observer<ResponseStatus<String>>() {
            @Override
            public void onChanged(ResponseStatus<String> stringResponseStatus) {
                if (stringResponseStatus.getResponseCode() == 0) {
                    ToastUtils.showShortToast(stringResponseStatus.getMsg());
                    mAccountRequester.getPointDetail();
                }
            }
        });
        mAccountRequester.getUserResultProject().observe(this, new Observer<ResponseStatus<UserDataBean>>() {
            @Override
            public void onChanged(ResponseStatus<UserDataBean> response) {
                if (response.getResponseCode() == 0) {
                    mStates.userDataBeanState.set(response.getData());
                    if (type == 1) {
                        mBinding.tvMinePointValue.setText(mStates.userDataBeanState.get().getPointSrc());
                        mBinding.tvMinePointFreezeValue.setText(mStates.userDataBeanState.get().getFreezePointsSrc());
                        mBinding.tvMinePointTitle.setText("当前消费积分");
                        mStates.typeTitleOne.set("兑换分红点");
                        mStates.typeTitleTow.set("消费积分转让");
                    } else {
                        mBinding.tvMinePointValue.setText(mStates.userDataBeanState.get().getHuitongTreasureSrc());
                        mBinding.tvMinePointFreezeValue.setText(mStates.userDataBeanState.get().getFreezeHuitongTreasureSrc());
                        mBinding.tvMinePointTitle.setText("当前惠通宝");
                        mStates.typeTitleOne.set("兑换消费积分");
                        mStates.typeTitleTow.set("惠通宝转让");
                    }
                }
            }
        });

        mAccountRequester.getPointBeanResult().observe(this, new Observer<ResponseStatus<PointListBean>>() {
            @Override
            public void onChanged(ResponseStatus<PointListBean> response) {
                if (response.getResponseCode() == 0) {

                    if (page == 1) {
                        mBinding.swipeRefreshLayout.finishRefresh();
                        mStates.pointsList.set(response.getData().getList());
                        if (!mStates.pointsList.get().isEmpty())
                            mBinding.ivListNotData.setVisibility(GONE);
                        else mBinding.ivListNotData.setVisibility(VISIBLE);
                    } else {
                        mBinding.swipeRefreshLayout.finishLoadMore();

                        List<PointListBean.ListBean> currentList = mStates.pointsList.get();
                        if (currentList != null) {
                            currentList.addAll(response.getData().getList());
                            mStates.pointsList.set(currentList);
                        }
                    }
                }
            }
        });

        mAccountRequester.getStringResult().observe(this, new Observer<ResponseStatus<Object>>() {
            @Override
            public void onChanged(ResponseStatus<Object> objectResponseStatus) {
                if (objectResponseStatus.getResponseCode() == 0) {

                    mStates.pointRate.set(objectResponseStatus.getData().toString());
                    if (null == dialog) {

                        dialog = new Dialog(MineConsumptionPointsActivity.this);
                        View view = View.inflate(MineConsumptionPointsActivity.this,
                                R.layout.dialog_consumption_point_exchange, null);
                        exchangeBinding = DataBindingUtil.bind(view);
                        exchangeBinding.setVm(mStates);
                        exchangeBinding.setClick(new ClickProxy());
                        dialog.setContentView(view);
                    }

                    Window window = dialog.getWindow();
                    window.setBackgroundDrawableResource(android.R.color.transparent);
                    WindowManager.LayoutParams lp = window.getAttributes();
                    lp.width = getResources().getDisplayMetrics().widthPixels;
                    window.setAttributes(lp);
                    window.setGravity(Gravity.BOTTOM); // 此处可以设置dialog显示的位置
                    dialog.show();


                    try {
                        if (StringUtil.isEmpty(mStates.pointRate.get()))
                            return;
                        String[] pointRate = mStates.pointRate.get().split(": ");
                        if (pointRate.length > 1) {
                            exchangeBinding.etDialogNumber.addTextChangedListener(new TextWatcher() {
                                @Override
                                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                                }

                                @Override
                                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                                    double price = exchangeBinding.etDialogNumber.getDoublePrice();
                                    DecimalFormat df = new DecimalFormat("#####0.000000");
                                    mStates.payPointPrice.set(df.format(price * Double.parseDouble(pointRate[1])));
                                }

                                @Override
                                public void afterTextChanged(Editable editable) {

                                }
                            });
                        }
                    } catch (Exception e) {
                        e.getMessage();
                    }
                }
            }
        });


        mBinding.swipeRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getDatas();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getDatas();
            }
        });

        mBinding.swipeRefreshLayout.autoRefresh();
    }

    private void getDatas() {
        mAccountRequester.getPointsBenefit(page, type);
    }

    DialogConsumptionPointExchangeBinding exchangeBinding;

    public static class ConsumptionPointsStates extends StateHolder {

        public final State<List<ListBean>> pointsList = new State<>(new ArrayList<>());
        public final State<UserDataBean> userDataBeanState = new State<>(new UserDataBean());


        public final State<String> pointNumber = new State<>("");//转让积分

        public final State<String> userId = new State<>("");//转让目标id
        public final State<String> pointRate = new State<>("");//积分费率
        public final State<String> pointRateUnit = new State<>("");//單位
        public final State<String> dialogTitle = new State<>("");//转让标题
        public final State<String> exchangeType = new State<>("");//转让类型
        public final State<String> exchangeTypeHint = new State<>("");//转让类型

        public final State<Integer> visibility = new State<>(VISIBLE);//
        public final State<Integer> payPoint = new State<>(GONE);//
        public final State<String> payPointPrice = new State<>("");//
        public final State<String> btnName = new State<>("");//
        public final State<String> typeTitleOne = new State<>("");//
        public final State<String> typeTitleTow = new State<>("");//
        public final State<String> describe = new State<>("");//
    }

    private Dialog dialog;

    public class ClickProxy {
        public void exchangePoint(int position) {

            if (type == 1) {
                if (position == 0) {
                    mStates.pointRateUnit.set("");
                    mStates.dialogTitle.set("分红点:消费积分比值");
                    mStates.exchangeType.set("兑换分红点");
                    mStates.exchangeTypeHint.set("兑换个数");
                    mStates.btnName.set("立即兑换");
                    mStates.describe.set("需支付积分");
                    mStates.visibility.set(GONE);
                    mStates.payPoint.set(VISIBLE);

                } else {
                    mStates.dialogTitle.set("转让费率");
                    mStates.exchangeTypeHint.set("转让个数");
                    mStates.exchangeType.set("转让消费积分数量");
                    mStates.pointRateUnit.set("+1个惠通宝");
                    mStates.btnName.set("立即转让");
                    mStates.visibility.set(VISIBLE);
                    mStates.payPoint.set(GONE);
                }
                mAccountRequester.getConsumptionPoints(position);
            } else {

                if (position == 0) {
                    mStates.pointRateUnit.set("");
                    mStates.dialogTitle.set("惠通宝:消费积分比值");
                    mStates.exchangeType.set("兑换消费积分");
                    mStates.exchangeTypeHint.set("兑换个数");
                    mStates.btnName.set("立即兑换");
                    mStates.describe.set("可兑换积分");
                    mStates.visibility.set(GONE);
                    mStates.payPoint.set(VISIBLE);

                } else {
                    mStates.dialogTitle.set("转让费率");
                    mStates.exchangeTypeHint.set("转让个数");
                    mStates.exchangeType.set("转让惠通宝数量");
                    mStates.pointRateUnit.set("+1个惠通宝");
                    mStates.btnName.set("立即转让");
                    mStates.visibility.set(VISIBLE);
                    mStates.payPoint.set(GONE);
                }
                mAccountRequester.getHTBTransferPointsConfig(position);
            }
        }

        public void submitExchangePoint() {


            if (null != dialog) {
                dialog.dismiss();
            }
            JsonObject params = new JsonObject();
            if (mStates.visibility.get() == VISIBLE) {


                if (StringUtil.isEmpty(mStates.pointNumber.get()) ||
                        StringUtil.isEmpty(mStates.userId.get())) {
                    ToastUtils.showShortToast("请正确输入转让信息");
                    return;
                }

                params.addProperty("userId", mStates.userId.get());
                params.addProperty("point", mStates.pointNumber.get());
                mAccountRequester.transferConsumptionVolume(params);

            } else {
                if (StringUtil.isEmpty(mStates.pointNumber.get())) {
                    ToastUtils.showShortToast("请正确输入兑换信息");
                    return;
                }
                params.addProperty("dividendPoint", mStates.pointNumber.get());
                mAccountRequester.redeemBonusPoints(params);
            }

        }
    }


}
